package com.lifu.yygh.msm.controller;

import com.lifu.yygh.common.result.Result;
import com.lifu.yygh.msm.service.MsmService;
import com.lifu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author lifu
 * @Date 2021/5/19 19:34
 */
@Api(tags = "用户手机登录接口")
@RestController
@RequestMapping(value = "/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @ApiOperation(value = "发送手机验证码")
    @GetMapping(value = "/send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码
        String code = redisTemplate.opsForValue().get(phone);//key手机号，value验证码
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //从redis获取不到验证码，生成验证码
        code = RandomUtil.getSixBitRandom();
        //通过短信服务发送
        boolean isSend = msmService.send(phone,code);
        //将验证码存放到redis
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }
}